#include "protocol.h"

#include <QList>
#include <QDebug>
#include <QDataStream>

PBS *mkPBS(uint MsgLen)
{
    uint PBSLen = sizeof (PBS) + MsgLen;
    PBS* pbs = (PBS*)malloc(PBSLen);

    if(NULL == pbs)
    {
        exit(EXIT_FAILURE); // 错误退出程序
    }
    memset (pbs, 0, PBSLen); // 数据初始化为0
    pbs -> PBSLen = PBSLen; // 数据参数初始化
    pbs -> MsgLen = MsgLen;

    return pbs;
}

PBS *serializeUserToPBS(const Core::User &user)
{
    // 将 User 的字段序列化到 QByteArray
    QByteArray buffer;

    // 序列化 `id`
    buffer.append(QString::number(user.id).toUtf8()).append('\0');

    // 序列化其他字段
    buffer.append(user.name.toUtf8()).append('\0');
    buffer.append(user.gender.toUtf8()).append('\0');
    buffer.append(user.birthDate.toUtf8()).append('\0');
    buffer.append(user.bio.toUtf8()).append('\0');
    buffer.append(user.password.toUtf8()).append('\0'); // 密码也序列化

    // 动态分配 PBS，包含 Msg 的实际长度
    uint msgLen = buffer.size();
    PBS* pbs = (PBS*)malloc(sizeof(PBS) + msgLen);
    if (pbs)
    {
        memset(pbs, 0, sizeof(PBS));              // 初始化固定部分为零
        memset(pbs->Msg, 0, msgLen);              // 初始化柔性数组部分为零
    }

    // 填充 PBS
    pbs->MsgType = 1;               // 示例消息类型
    pbs->MsgLen = msgLen;
    pbs->PBSLen = sizeof(PBS) + msgLen;
    pbs->Code = 1;
//    memset(pbs->caData, 0, sizeof(pbs->caData)); // 填充保留字段
    memcpy(pbs->Msg, buffer.data(), msgLen);     // 拷贝数据

    return pbs;
}

Core::User deserializePBSToUser(const PBS *pbs)
{
    // 从 PBS 的 Msg 中读取数据
    QByteArray data((const char*)pbs->Msg, pbs->MsgLen);
    QList<QByteArray> fields = data.split('\0'); // 按 '\0' 分割字段

    int ret = pbs->Code;
    Core::User user;
    if (fields.size() >= 4)
    {
        user.id = fields[0].toInt();
        user.name = QString::fromUtf8(fields[1]);
        user.gender = QString::fromUtf8(fields[2]);
        user.birthDate = QString::fromUtf8(fields[3]);
        user.bio = QString::fromUtf8(fields[4]);
        user.password = QString::fromUtf8(fields[5]);
    }
    return user;
}

PBS *serializeAnimeToPBS(const Core::Anime &anime)
{
    QByteArray buffer;

    // 将每个字段序列化为字节流
    buffer.append(QString::number(anime.id).toUtf8()).append('\0');
    buffer.append(anime.title.toUtf8()).append('\0');
    buffer.append(anime.releaseDate.toUtf8()).append('\0');
    buffer.append(anime.synopsis.toUtf8()).append('\0');
    buffer.append(anime.staff.toUtf8()).append('\0');
    buffer.append(anime.watchLink.toUtf8()).append('\0');

    // 序列化声优、
    buffer.append(QString::number(anime.voiceCast.size()).toUtf8()).append('\0');
    for(auto p : anime.voiceCast)
    {
        buffer.append(p.toUtf8()).append('\0');
    }

    // 序列化标签
    buffer.append(QString::number(anime.tags.size()).toUtf8()).append('\0');
    for(auto p : anime.tags)
    {
        buffer.append(p.toUtf8()).append('\0');
    }


    // 序列化评论
    for (const Core::Comment& comment : anime.comments)
    {
        buffer.append(QString::number(comment.id).toUtf8()).append('\0');
        buffer.append(QString::number(comment.animeId).toUtf8()).append('\0');
        buffer.append(QString::number(comment.userId).toUtf8()).append('\0');
        buffer.append(comment.userName.toUtf8()).append('\0');
        buffer.append(comment.content.toUtf8()).append('\0');
        buffer.append(comment.createdAt.toUtf8()).append('\0');
    }

    uint msgLen = buffer.size();
    size_t totalSize = sizeof(PBS) + msgLen;

    // 动态分配内存
    PBS* pbs = (PBS*)malloc(totalSize);
    if (!pbs)
    {
        qCritical() << "Memory allocation failed for PBS!";
        return nullptr;
    }

    // 初始化 PBS 的固定字段
    memset(pbs, 0, sizeof(PBS));
    pbs->MsgType = 1; // 假设 MsgType 是 1
    pbs->MsgLen = msgLen;
    pbs->PBSLen = totalSize;

    // 将序列化后的数据拷贝到 Msg
    memcpy(pbs->Msg, buffer.data(), msgLen);

    qDebug() << "Serialized PBS for Anime:" << buffer;

    return pbs;
}

Core::Anime deserializePBSToAnime(const PBS *pbs)
{
    // 从 PBS 的 Msg 中读取数据
    QByteArray data((const char*)pbs->Msg, pbs->MsgLen);
    QList<QByteArray> fields = data.split('\0');  // 按 '\0' 分割字段

    Core::Anime anime;
    QVector<Core::Comment> comments;

    // 假设 PBS 中字段顺序依次是：id, title, releaseDate, synopsis, staff, voiceCast, watchLink, tag
    int index = 0;

    // 解析动漫基础信息
    bool ok;
    anime.id = fields[index++].toInt(&ok);
    if (!ok)
    {
        qWarning() << "Failed to parse anime id";
    }

    anime.title = QString(fields[index++]);
    anime.releaseDate = QString(fields[index++]);
    anime.synopsis = QString(fields[index++]);
    anime.staff = QString(fields[index++]);
    anime.watchLink = QString(fields[index++]);

    int castCount = fields[index++].toInt(&ok);
    for(int i = 0; i < castCount; i++)
    {
        QString cast = QString(fields[index++]);
        anime.voiceCast.append(cast);
    }

    int tagCount = fields[index++].toInt(&ok);
    for(int i = 0; i < tagCount; i++)
    {
        QString tag = QString(fields[index++]);
        anime.tags.append(tag);
    }


    // 解析评论部分
    // 假设评论数作为最后一个字段存储（可以根据实际情况调整）
    int commentCount = fields[index++].toInt(&ok);
    if (!ok)
    {
        qWarning() << "Failed to parse comment count";
    }

    // 解析评论
    for (int i = 0; i < commentCount; ++i)
    {
        Core::Comment comment;
        comment.id = fields[index++].toInt(&ok);
        if (!ok)
        {
            qWarning() << "Failed to parse comment id";
        }

        comment.animeId = fields[index++].toInt(&ok);
        if (!ok)
        {
            qWarning() << "Failed to parse comment animeId";
        }

        comment.userId = fields[index++].toInt(&ok);
        if (!ok)
        {
            qWarning() << "Failed to parse comment userId";
        }

        comment.userName = QString(fields[index++]);
        comment.content = QString(fields[index++]);
        comment.createdAt = QString(fields[index++]);

        comments.append(comment);
    }

    anime.comments = comments;

    qDebug() << "Deserialized Anime:" << anime.title;
    return anime;
}

PBS* serializeAnimesToPBS(const QList<Core::Anime>& animes)
{
    QByteArray buffer;

    // 将每个字段序列化为字节流
    int size = animes.size();
    buffer.append(QString::number(size).toUtf8()).append('\0');
    for(int i = 0; i < size; i++)
    {
        Core::Anime anime = animes[i];

        buffer.append(QString::number(anime.id).toUtf8()).append('\0');
        buffer.append(anime.title.toUtf8()).append('\0');
        buffer.append(anime.releaseDate.toUtf8()).append('\0');
        buffer.append(anime.synopsis.toUtf8()).append('\0');
        buffer.append(anime.staff.toUtf8()).append('\0');
        buffer.append(anime.watchLink.toUtf8()).append('\0');

        // 序列化声优、
        buffer.append(QString::number(anime.voiceCast.size()).toUtf8()).append('\0');
        for(auto p : anime.voiceCast)
        {
            buffer.append(p.toUtf8()).append('\0');
        }

        // 序列化标签
        buffer.append(QString::number(anime.tags.size()).toUtf8()).append('\0');
        for(auto p : anime.tags)
        {
            buffer.append(p.toUtf8()).append('\0');
        }

        buffer.append(QString::number(anime.comments.size()).toUtf8()).append('\0');

        // 序列化评论
        for (const Core::Comment& comment : anime.comments)
        {
            buffer.append(QString::number(comment.id).toUtf8()).append('\0');
            buffer.append(QString::number(comment.animeId).toUtf8()).append('\0');
            buffer.append(QString::number(comment.userId).toUtf8()).append('\0');
            buffer.append(comment.userName.toUtf8()).append('\0');
            buffer.append(comment.content.toUtf8()).append('\0');
            buffer.append(comment.createdAt.toUtf8()).append('\0');
        }
    }

    uint msgLen = buffer.size();
    size_t totalSize = sizeof(PBS) + msgLen;

    // 动态分配内存
    PBS* pbs = (PBS*)malloc(totalSize);
    if (!pbs)
    {
        qCritical() << "Memory allocation failed for PBS!";
        return nullptr;
    }

    // 初始化 PBS 的固定字段
    memset(pbs, 0, sizeof(PBS));
    pbs->MsgType = 1; // 假设 MsgType 是 1
    pbs->MsgLen = msgLen;
    pbs->PBSLen = totalSize;

    // 将序列化后的数据拷贝到 Msg
    memcpy(pbs->Msg, buffer.data(), msgLen);

    qDebug() << "Serialized PBS for Anime:" << buffer;

    return pbs;
}
QList<Core::Anime> deserializePBSToAnims(const PBS *pbs)
{
    // 从 PBS 的 Msg 中读取数据
    QByteArray data((const char*)pbs->Msg, pbs->MsgLen);
    QList<QByteArray> fields = data.split('\0');  // 按 '\0' 分割字段


    QList<Core::Anime> animes;

    int index = 0;
    bool ok;

    int size = fields[index++].toInt(&ok);

    for(int i = 0; i < size; i++)
    {
        Core::Anime anime;
        QVector<Core::Comment> comments;

        // 假设 PBS 中字段顺序依次是：id, title, releaseDate, synopsis, staff, voiceCast, watchLink, tag


        // 解析动漫基础信息

        anime.id = fields[index++].toInt(&ok);
        if (!ok)
        {
            qWarning() << "Failed to parse anime id";
        }

        anime.title = QString(fields[index++]);
        anime.releaseDate = QString(fields[index++]);
        anime.synopsis = QString(fields[index++]);
        anime.staff = QString(fields[index++]);
        anime.watchLink = QString(fields[index++]);

        int castCount = fields[index++].toInt(&ok);
        for(int i = 0; i < castCount; i++)
        {
            QString cast = QString(fields[index++]);
            anime.voiceCast.append(cast);
        }

        int tagCount = fields[index++].toInt(&ok);
        for(int i = 0; i < tagCount; i++)
        {
            QString tag = QString(fields[index++]);
            anime.tags.append(tag);
        }

        // 解析评论部分
        // 假设评论数作为最后一个字段存储（可以根据实际情况调整）
        int commentCount = fields[index++].toInt(&ok);
        if (!ok)
        {
            qWarning() << "Failed to parse comment count";
        }

        // 解析评论
        for (int i = 0; i < commentCount; ++i)
        {
            Core::Comment comment;
            comment.id = fields[index++].toInt(&ok);
            if (!ok)
            {
                qWarning() << "Failed to parse comment id";
            }

            comment.animeId = fields[index++].toInt(&ok);
            if (!ok)
            {
                qWarning() << "Failed to parse comment animeId";
            }

            comment.userId = fields[index++].toInt(&ok);
            if (!ok)
            {
                qWarning() << "Failed to parse comment userId";
            }

            comment.userName = QString(fields[index++]);
            comment.content = QString(fields[index++]);
            comment.createdAt = QString(fields[index++]);

            comments.append(comment);
        }

        anime.comments = comments;

        animes.append(anime);
    }


    return animes;
}

PBS* serializeCommentToPBS(const Core::Comment& comment)
{
    QByteArray buffer;

    // 将每个字段序列化为字节流
    buffer.append(QString::number(comment.id).toUtf8()).append('\0');
    buffer.append(QString::number(comment.animeId).toUtf8()).append('\0');
    buffer.append(QString::number(comment.userId).toUtf8()).append('\0');
    buffer.append(comment.userName.toUtf8()).append('\0');
    buffer.append(comment.content.toUtf8()).append('\0');
    buffer.append(comment.createdAt.toUtf8()).append('\0');

    uint msgLen = buffer.size();
    size_t totalSize = sizeof(PBS) + msgLen;

    // 动态分配内存
    PBS* pbs = (PBS*)malloc(totalSize);
    if (!pbs)
    {
        qCritical() << "Memory allocation failed for PBS!";
        return nullptr;
    }

    // 初始化 PBS 的固定字段
    memset(pbs, 0, sizeof(PBS));
    pbs->MsgType = 1; // 假设 MsgType 是 1
    pbs->MsgLen = msgLen;
    pbs->PBSLen = totalSize;

    // 将序列化后的数据拷贝到 Msg
    memcpy(pbs->Msg, buffer.data(), msgLen);

    qDebug() << "Serialized PBS for Anime:" << buffer;

    return pbs;
}

Core::Comment deserializePBSToComment(const PBS *pbs)
{
    // 从 PBS 的 Msg 中读取数据
    QByteArray data((const char*)pbs->Msg, pbs->MsgLen);
    QList<QByteArray> fields = data.split('\0');  // 按 '\0' 分割字段

    Core::Comment comment;
    QVector<Core::Comment> comments;

    // 假设 PBS 中字段顺序依次是：id, title, releaseDate, synopsis, staff, voiceCast, watchLink, tag
    int index = 0;

    // 解析动漫基础信息
    bool ok;
    comment.id = fields[index++].toInt(&ok);
    if (!ok)
    {
        qWarning() << "Failed to parse  id";
    }
    comment.animeId = fields[index++].toInt(&ok);
    if (!ok)
    {
        qWarning() << "Failed to parse anime id";
    }
    comment.userId = fields[index++].toInt(&ok);
    if (!ok)
    {
        qWarning() << "Failed to parse userId";
    }

    comment.userName = QString(fields[index++]);
    comment.content = QString(fields[index++]);
    comment.createdAt = QString(fields[index++]);

    return comment;

}

PBS* serializePostCommentsToPBS(const QList<Core::Comment>& comments)
{
    QByteArray buffer;

    buffer.append(QString::number(comments.size()).toUtf8()).append('\0');

    for(auto &p  : comments)
    {
        // 将每个字段序列化为字节流
        buffer.append(QString::number(p.id).toUtf8()).append('\0');
        buffer.append(QString::number(p.animeId).toUtf8()).append('\0');
        buffer.append(QString::number(p.userId).toUtf8()).append('\0');
        buffer.append(p.userName.toUtf8()).append('\0');
        buffer.append(p.content.toUtf8()).append('\0');
        buffer.append(p.createdAt.toUtf8()).append('\0');
    }

    uint msgLen = buffer.size();
    size_t totalSize = sizeof(PBS) + msgLen;

    // 动态分配内存
    PBS* pbs = (PBS*)malloc(totalSize);
    if (!pbs)
    {
        qCritical() << "Memory allocation failed for PBS!";
        return nullptr;
    }

    // 初始化 PBS 的固定字段
    memset(pbs, 0, sizeof(PBS));
    pbs->MsgType = 1; // 假设 MsgType 是 1
    pbs->MsgLen = msgLen;
    pbs->PBSLen = totalSize;

    // 将序列化后的数据拷贝到 Msg
    memcpy(pbs->Msg, buffer.data(), msgLen);

    qDebug() << "Serialized PBS for Anime:" << buffer;

    return pbs;
}
QList<Core::Comment> deserializePBSToPostComments(const PBS *pbs)
{
    // 从 PBS 的 Msg 中读取数据
    QByteArray data((const char*)pbs->Msg, pbs->MsgLen);
    QList<QByteArray> fields = data.split('\0');  // 按 '\0' 分割字段

    Core::Comment comment;
    QList<Core::Comment> comments;

    // 假设 PBS 中字段顺序依次是：id, title, releaseDate, synopsis, staff, voiceCast, watchLink, tag
    int index = 0;

    int count =  fields[index++].toInt();
    for(int i = 0; i < count; i++)
    {
        // 解析动漫基础信息
        bool ok;
        comment.id = fields[index++].toInt(&ok);
        if (!ok)
        {
            qWarning() << "Failed to parse  id";
        }
        comment.animeId = fields[index++].toInt(&ok);
        if (!ok)
        {
            qWarning() << "Failed to parse anime id";
        }
        comment.userId = fields[index++].toInt(&ok);
        if (!ok)
        {
            qWarning() << "Failed to parse userId";
        }

        comment.userName = QString(fields[index++]);
        comment.content = QString(fields[index++]);
        comment.createdAt = QString(fields[index++]);

        comments.append(comment);
    }



    return comments;
}

PBS* serializeFilterToPBS(const Core::Filter& filter)
{
    QByteArray buffer;

    // 将每个字段序列化为字节流
    buffer.append(QString::number(filter.tag.size()).toUtf8()).append('\0');
    for(auto &p : filter.tag)
    {
        buffer.append(p.toUtf8()).append('\0');
    }
    buffer.append(QString::number(filter.year.size()).toUtf8()).append('\0');
    for(auto &p : filter.year)
    {
        buffer.append(p.toUtf8()).append('\0');
    }

    uint msgLen = buffer.size();
    size_t totalSize = sizeof(PBS) + msgLen;

    // 动态分配内存
    PBS* pbs = (PBS*)malloc(totalSize);
    if (!pbs)
    {
        qCritical() << "Memory allocation failed for PBS!";
        return nullptr;
    }

    // 初始化 PBS 的固定字段
    memset(pbs, 0, sizeof(PBS));
    pbs->MsgType = 1; // 假设 MsgType 是 1
    pbs->MsgLen = msgLen;
    pbs->PBSLen = totalSize;

    // 将序列化后的数据拷贝到 Msg
    memcpy(pbs->Msg, buffer.data(), msgLen);

    qDebug() << "Serialized PBS for Anime:" << buffer;

    return pbs;
}
Core::Filter deserializePBSToFilter(const PBS *pbs)
{
    // 从 PBS 的 Msg 中读取数据
    QByteArray data((const char*)pbs->Msg, pbs->MsgLen);
    QList<QByteArray> fields = data.split('\0');  // 按 '\0' 分割字段

    Core::Filter filter;

    // 假设 PBS 中字段顺序依次是：id, title, releaseDate, synopsis, staff, voiceCast, watchLink, tag
    int index = 0;

    int tagCount = fields[index++].toInt();
    for(int i = 0; i < tagCount; i++)
    {
        filter.tag.append(QString(fields[index++]));
    }
    int yearCount = fields[index++].toInt();
    for(int i = 0; i < yearCount; i++)
    {
        filter.year.append(QString(fields[index++]));
    }


    return filter;
}

PBS *serializeQStringToPBS(const QString &str)
{
    // 获取字符串的长度
    uint msgLen = str.toUtf8().size();  // 获取 UTF-8 编码后的字节数

    // 分配内存来存储 PBS 结构和动态消息内容
    PBS* pbs = (PBS*)malloc(sizeof(PBS) + msgLen);  // 分配动态数组空间

    if (pbs == nullptr)
    {
        return nullptr;  // 内存分配失败
    }

    // 设置 PBS 的基本字段
    pbs->PBSLen = sizeof(PBS) + msgLen;  // 总协议单元大小，包括 Msg
    pbs->MsgType = 0;  // 设置消息类型，按需调整
    pbs->Code = 0;     // 设置状态码，按需调整
    pbs->MsgLen = msgLen;

    // 将 QString 转换为 UTF-8 字节数组，并复制到 Msg 字段
    QByteArray byteArray = str.toUtf8();
    memcpy(pbs->Msg, byteArray.constData(), msgLen);  // 复制消息内容到 Msg

    return pbs;
}

QString deserializePBSToQString(const PBS *pbs)
{
    if (pbs == nullptr || pbs->Msg == nullptr)
    {
        return QString();  // 如果指针无效，返回空字符串
    }

    // 将 Msg 字段转换为 QByteArray
    QByteArray byteArray(pbs->Msg, pbs->MsgLen);

    // 使用 UTF-8 解码为 QString
    return QString::fromUtf8(byteArray);
}

PBS *serializePostToPBS(const Core::Post &post)
{
    QByteArray buffer;

    // 序列化 Post 的基本字段
    buffer.append(QString::number(post.id).toUtf8()).append('\0');
    buffer.append(QString::number(post.userId).toUtf8()).append('\0');
    buffer.append(post.userName.toUtf8()).append('\0');
    buffer.append(post.title.toUtf8()).append('\0');
    buffer.append(post.content.toUtf8()).append('\0');
    buffer.append(post.createdAt.toUtf8()).append('\0');
    buffer.append(QString::number(post.likeCount).toUtf8()).append('\0');
    buffer.append(QString::number(post.userLiked).toUtf8()).append('\0');

    // 序列化评论
    buffer.append(QString::number(post.comments.size()).toUtf8()).append('\0');  // 评论数量

    for (const auto& comment : post.comments)
    {
        buffer.append(QString::number(comment.id).toUtf8()).append('\0');
        buffer.append(QString::number(comment.postId).toUtf8()).append('\0');
        buffer.append(QString::number(comment.userId).toUtf8()).append('\0');
        buffer.append(comment.userName.toUtf8()).append('\0');
        buffer.append(comment.content.toUtf8()).append('\0');
        buffer.append(comment.createdAt.toUtf8()).append('\0');
    }
    // 序列化点赞
    buffer.append(QString::number(post.likes.size()).toUtf8()).append('\0');  // 评论数量

    for (const auto& like : post.likes)
    {
        buffer.append(QString::number(like.id).toUtf8()).append('\0');
        buffer.append(QString::number(like.postId).toUtf8()).append('\0');
        buffer.append(QString::number(like.userId).toUtf8()).append('\0');
        buffer.append(like.userName.toUtf8()).append('\0');
        buffer.append(like.createdAt.toUtf8()).append('\0');
    }

    // 分配足够的内存并创建 PBS
    PBS* pbs = (PBS*)malloc(sizeof(PBS) + buffer.size());
    if (pbs)
    {
        pbs->PBSLen = sizeof(PBS) + buffer.size();
        pbs->MsgType = POST_REQUEST;  // 设置相应的消息类型
        pbs->Code = 0;  // 可以根据需要设置
        pbs->MsgLen = buffer.size();
        memcpy(pbs->Msg, buffer.constData(), buffer.size());  // 将数据复制到 Msg
    }

    return pbs;
}

Core::Post deserializePBSToPost(const PBS *pbs)
{
    Core::Post post;
    QByteArray data((const char*)pbs->Msg, pbs->MsgLen);
    QByteArrayList fields = data.split('\0');  // 按 '\0' 分割字段

    if (fields.size() < 8)
    {
        return post;  // 数据格式不正确，返回空的 Post 对象
    }

    int index = 0;
    post.id = fields[index++].toInt();
    post.userId = fields[index++].toInt();
    post.userName = QString::fromUtf8(fields[index++]);
    post.title = QString::fromUtf8(fields[index++]);
    post.content = QString::fromUtf8(fields[index++]);
    post.createdAt = QString::fromUtf8(fields[index++]);
    post.likeCount = fields[index++].toInt();
    post.userLiked = fields[index++].toInt();
    post.pixSize = fields[index++].toUInt();

    int commentCount = fields[index++].toInt();  // 获取评论数量

    for (int i = 0; i < commentCount; ++i)
    {

        Core::PostComment comment;
        comment.id = fields[index++].toInt();
        comment.postId = fields[index++].toInt();
        comment.userId = fields[index++].toInt();
        comment.userName = QString::fromUtf8(fields[index++]);
        comment.content = QString::fromUtf8(fields[index++]);
        comment.createdAt = QString::fromUtf8(fields[index++]);

        post.comments.append(comment);
    }

    int likesCount = fields[index++].toInt();  // 获取评论数量
    for (int i = 0; i < likesCount; ++i)
    {

        Core::LikePost like;
        like.id = fields[index++].toInt();
        like.postId = fields[index++].toInt();
        like.userId = fields[index++].toInt();
        like.userName = QString::fromUtf8(fields[index++]);
        like.createdAt = QString::fromUtf8(fields[index++]);

        post.likes.append(like);
    }

    return post;
}

PBS* serializePostsToPBS(const QList<Core::Post>& posts)
{
    QByteArray buffer;

    // 序列化帖子数量
    int size = posts.size();
    buffer.append(QString::number(size).toUtf8()).append('\0');

    for (const Core::Post& post : posts)
    {
        // 序列化帖子基本字段
        buffer.append(QString::number(post.id).toUtf8()).append('\0');
        buffer.append(QString::number(post.userId).toUtf8()).append('\0');
        buffer.append(post.userName.toUtf8()).append('\0');
        buffer.append(post.title.toUtf8()).append('\0');
        buffer.append(post.content.toUtf8()).append('\0');
        buffer.append(post.createdAt.toUtf8()).append('\0');
        buffer.append(QString::number(post.likeCount).toUtf8()).append('\0');
        buffer.append(QString::number(post.userLiked).toUtf8()).append('\0');

        // 序列化评论
        buffer.append(QString::number(post.comments.size()).toUtf8()).append('\0');
        for (const Core::PostComment& comment : post.comments)
        {
            buffer.append(QString::number(comment.id).toUtf8()).append('\0');
            buffer.append(QString::number(comment.postId).toUtf8()).append('\0');
            buffer.append(QString::number(comment.userId).toUtf8()).append('\0');
            buffer.append(comment.userName.toUtf8()).append('\0');
            buffer.append(comment.content.toUtf8()).append('\0');
            buffer.append(comment.createdAt.toUtf8()).append('\0');
        }

        // 序列化点赞
        buffer.append(QString::number(post.likes.size()).toUtf8()).append('\0');  // 评论数量

        for (const auto& like : post.likes)
        {
            buffer.append(QString::number(like.id).toUtf8()).append('\0');
            buffer.append(QString::number(like.postId).toUtf8()).append('\0');
            buffer.append(QString::number(like.userId).toUtf8()).append('\0');
            buffer.append(like.userName.toUtf8()).append('\0');
            buffer.append(like.createdAt.toUtf8()).append('\0');
        }
    }

    // 分配足够的内存并创建 PBS
    PBS* pbs = (PBS*)malloc(sizeof(PBS) + buffer.size());
    if (pbs)
    {
        pbs->PBSLen = sizeof(PBS) + buffer.size();
        pbs->MsgType = POST_REQUEST;  // 设置相应的消息类型
        pbs->Code = 0;  // 可以根据需要设置
        pbs->MsgLen = buffer.size();
        memcpy(pbs->Msg, buffer.constData(), buffer.size());  // 将数据复制到 Msg
    }

    return pbs;
}

QList<Core::Post> deserializePBSToPosts(const PBS *pbs)
{
    QByteArray data((const char*)pbs->Msg, pbs->MsgLen);
    QList<QByteArray> fields = data.split('\0');

    QList<Core::Post> posts;
    int index = 0;

    if (fields.isEmpty())
    {
        qCritical() << "Invalid PBS data: empty fields";
        return posts;
    }

    // 获取帖子数量
    bool ok = false;
    int size = fields[index++].toInt(&ok);
    if (!ok || size < 0)
    {
        qCritical() << "Failed to parse post count";
        return posts;
    }

    for (int i = 0; i < size; i++)
    {
        Core::Post post;

        // 解析帖子基本字段
        post.id = fields[index++].toInt(&ok);
        post.userId = fields[index++].toInt(&ok);
        post.userName = QString::fromUtf8(fields[index++]);
        post.title = QString::fromUtf8(fields[index++]);
        post.content = QString::fromUtf8(fields[index++]);
        post.createdAt = QString::fromUtf8(fields[index++]);
        post.likeCount = fields[index++].toInt(&ok);
        post.userLiked = fields[index++].toInt(&ok);

        // 解析评论
        int commentCount = fields[index++].toInt(&ok);
        for (int j = 0; j < commentCount; j++)
        {
            Core::PostComment comment;
            comment.id = fields[index++].toInt(&ok);
            comment.postId = fields[index++].toInt(&ok);
            comment.userId = fields[index++].toInt(&ok);
            comment.userName = QString::fromUtf8(fields[index++]);
            comment.content = QString::fromUtf8(fields[index++]);
            comment.createdAt = QString::fromUtf8(fields[index++]);

            post.comments.append(comment);
        }

        int likesCount = fields[index++].toInt();  // 获取评论数量
        for (int i = 0; i < likesCount; ++i)
        {

            Core::LikePost like;
            like.id = fields[index++].toInt();
            like.postId = fields[index++].toInt();
            like.userId = fields[index++].toInt();
            like.userName = QString::fromUtf8(fields[index++]);
            like.createdAt = QString::fromUtf8(fields[index++]);

            post.likes.append(like);
        }

        posts.append(post);
    }



    return posts;
}

PBS *serializePostCommentToPBS(const Core::PostComment &comment)
{
    QByteArray buffer;

    // 将每个字段序列化为字节流
    buffer.append(QString::number(comment.id).toUtf8()).append('\0');
    buffer.append(QString::number(comment.postId).toUtf8()).append('\0');
    buffer.append(QString::number(comment.userId).toUtf8()).append('\0');
    buffer.append(comment.userName.toUtf8()).append('\0');
    buffer.append(comment.content.toUtf8()).append('\0');
    buffer.append(comment.createdAt.toUtf8()).append('\0');

    uint msgLen = buffer.size();
    size_t totalSize = sizeof(PBS) + msgLen;

    // 动态分配内存
    PBS* pbs = (PBS*)malloc(totalSize);
    if (!pbs)
    {
        qCritical() << "Memory allocation failed for PBS!";
        return nullptr;
    }

    // 初始化 PBS 的固定字段
    memset(pbs, 0, sizeof(PBS));
    pbs->MsgType = 1; // 假设 MsgType 是 1
    pbs->MsgLen = msgLen;
    pbs->PBSLen = totalSize;

    // 将序列化后的数据拷贝到 Msg
    memcpy(pbs->Msg, buffer.data(), msgLen);

    qDebug() << "Serialized PBS for Anime:" << buffer;

    return pbs;
}

Core::PostComment deserializePBSToPostComment(const PBS *pbs)
{
    // 从 PBS 的 Msg 中读取数据
    QByteArray data((const char*)pbs->Msg, pbs->MsgLen);
    QList<QByteArray> fields = data.split('\0');  // 按 '\0' 分割字段

    Core::PostComment comment;

    // 假设 PBS 中字段顺序依次是：id, title, releaseDate, synopsis, staff, voiceCast, watchLink, tag
    int index = 0;

    // 解析动漫基础信息
    bool ok;
    comment.id = fields[index++].toInt(&ok);
    if (!ok)
    {
        qWarning() << "Failed to parse  id";
    }
    comment.postId = fields[index++].toInt(&ok);
    if (!ok)
    {
        qWarning() << "Failed to parse anime id";
    }
    comment.userId = fields[index++].toInt(&ok);
    if (!ok)
    {
        qWarning() << "Failed to parse userId";
    }

    comment.userName = QString(fields[index++]);
    comment.content = QString(fields[index++]);
    comment.createdAt = QString(fields[index++]);

    return comment;
}


PBS *serializeLikePostToPBS(const Core::LikePost &like)
{
    QByteArray buffer;

    // 将每个字段序列化为字节流
    buffer.append(QString::number(like.id).toUtf8()).append('\0');
    buffer.append(QString::number(like.postId).toUtf8()).append('\0');
    buffer.append(QString::number(like.userId).toUtf8()).append('\0');
    buffer.append(like.userName.toUtf8()).append('\0');
    buffer.append(like.createdAt.toUtf8()).append('\0');


    uint msgLen = buffer.size();
    size_t totalSize = sizeof(PBS) + msgLen;

    // 动态分配内存
    PBS* pbs = (PBS*)malloc(totalSize);
    if (!pbs)
    {
        qCritical() << "Memory allocation failed for PBS!";
        return nullptr;
    }

    // 初始化 PBS 的固定字段
    memset(pbs, 0, sizeof(PBS));
    pbs->MsgType = 1; // 假设 MsgType 是 1
    pbs->MsgLen = msgLen;
    pbs->PBSLen = totalSize;

    // 将序列化后的数据拷贝到 Msg
    memcpy(pbs->Msg, buffer.data(), msgLen);

    qDebug() << "Serialized PBS for Anime:" << buffer;

    return pbs;
}

Core::LikePost deserializePBSToLikePost(const PBS *pbs)
{
    // 从 PBS 的 Msg 中读取数据
    QByteArray data((const char*)pbs->Msg, pbs->MsgLen);
    QList<QByteArray> fields = data.split('\0');  // 按 '\0' 分割字段

    Core::LikePost like;

    // 假设 PBS 中字段顺序依次是：id, title, releaseDate, synopsis, staff, voiceCast, watchLink, tag
    int index = 0;

    // 解析动漫基础信息
    bool ok;
    like.id = fields[index++].toInt(&ok);
    if (!ok)
    {
        qWarning() << "Failed to parse  id";
    }
    like.postId = fields[index++].toInt(&ok);
    if (!ok)
    {
        qWarning() << "Failed to parse anime id";
    }
    like.userId = fields[index++].toInt(&ok);
    if (!ok)
    {
        qWarning() << "Failed to parse anime id";
    }
    like.userName = QString(fields[index++]);
    like.createdAt = QString(fields[index++]);


    return like;
}


PBS *serializePixFromPostToPBS(const Core::PixFromPost &pixFromPost)
{
    size_t pbsSize = sizeof(PBS) + sizeof(pixFromPost.postId) + pixFromPost.pix_buf.size();

    PBS* pbs = (PBS*)malloc(pbsSize);
    if (!pbs)
    {
        return nullptr;
    }

    pbs->PBSLen = static_cast<uint>(pbsSize);
    pbs->MsgType = PIX_FROM_POST_SEND;

    size_t msgOffset = sizeof(PBS);

    memcpy(pbs->Msg, &pixFromPost.postId, sizeof(pixFromPost.postId));
    msgOffset += sizeof(pixFromPost.postId);

    if (!pixFromPost.pix_buf.isEmpty())
    {
        memcpy(pbs->Msg + sizeof(pixFromPost.postId), pixFromPost.pix_buf.data(), pixFromPost.pix_buf.size());
        msgOffset += pixFromPost.pix_buf.size();
    }

    pbs->MsgLen = static_cast<uint>(msgOffset - sizeof(PBS));
    return pbs;
}

Core::PixFromPost deserializePBSToPixFromPost(const PBS *pbs)
{
    Core::PixFromPost pixFromPost;

    if (!pbs || pbs->PBSLen < sizeof(PBS) || pbs->MsgLen < sizeof(int))
    {
        qWarning() << "Invalid PBS data!";
        return pixFromPost;
    }

    pixFromPost.postId = *(int*)(pbs->Msg);
    size_t pixBufSize = pbs->MsgLen - sizeof(int);
    if (pixBufSize > 0)
    {
        pixFromPost.pix_buf = QByteArray(pbs->Msg + sizeof(int), pixBufSize);
    }

    return pixFromPost;
}
